package cn.chencaiju.day13;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ProducerAndConsumer {
	public static void main(String[] args) {
		ExecutorService service=Executors.newFixedThreadPool(2);
		Factory f=new Factory();
		service.execute(new Producer(f));
		service.execute(new Consumer(f));
		service.shutdown();
	}
}
class Producer implements Runnable{
	private Factory f;
	
	public Producer(Factory f) {
		super();
		this.f = f;
	}

	@Override
	public void run() {
		try {
			while(true) {
				f.put();
				Thread.sleep((int) (Math.random()*3000));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
class Consumer implements Runnable{
	private Factory f;
	
	public Consumer(Factory f) {
		super();
		this.f = f;
	}

	@Override
	public void run() {
		try {
			while(true) {
				f.buy();
				Thread.sleep((int)(Math.random()*3000));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
class Factory{
	private static final int MAX=10;
	List<Integer> eggs=new ArrayList<>();
	private int id=1;
	public synchronized void buy() {
		if(eggs.isEmpty()) {
			System.out.println("鸡还没有下蛋！");
			try {
				wait();//线程进入等待状态，释放资源
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			int last=eggs.remove(eggs.size()-1);
			System.out.println("买了一个鸡蛋。。。"+last);
			notify();//唤醒线程
		}
	}
	public synchronized void put() {
		if(eggs.size()>=MAX) {
			System.out.println("鸡蛋太多了！");
			try {
				wait();//线程进入等待状态，释放资源
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			eggs.add(id++);
			System.out.println("生产一个鸡蛋。。。"+id);
			notify();//唤醒线程
		}
	}
}